package com.buka.config;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class SentinelExceptionHandler {

    @ExceptionHandler(BlockException.class)
    @ResponseBody
    public void handleBlockException(HttpServletResponse response, BlockException ex) throws IOException {
        System.out.println("通过 ControllerAdvice 捕获 Sentinel 异常：" + ex.getClass().getName());
        response.setContentType("application/json;charset=utf-8");
        if (ex instanceof FlowException) {
            response.getWriter().print("{\"code\": 429, \"message\": \"请求被限流，请稍后再试\"}");
        } else if (ex instanceof DegradeException) {
            response.getWriter().print("{\"code\": 503, \"message\": \"服务暂时不可用，请稍后再试\"}");
        } else if (ex instanceof ParamFlowException) {
            response.getWriter().print("{\"code\": 400, \"message\": \"参数限流，请检查参数\"}");
        } else if (ex instanceof SystemBlockException) {
            response.getWriter().print("{\"code\": 500, \"message\": \"系统负载过高，请稍后再试\"}");
        } else if (ex instanceof AuthorityException) {
            response.getWriter().print("{\"code\": 403, \"message\": \"没有权限访问\"}");
        }
    }
}